<template>
  <div class="app-container">
    <div class="header">
      <el-form
        :inline="true"
        :model="form"
        class="demo-form-inline"
        style="justify-content: space-between"
        ref="ruleFormRef"
      >
        <el-form-item label="用户昵称" prop="nickName">
          <el-input v-model="form.nickName" disabled />
        </el-form-item>
        <el-form-item label="登录账号" prop="username">
          <el-input v-model="form.username" disabled />
        </el-form-item>
      </el-form>
    </div>
    <div class="footer">
      <div class="util">
        <el-button type="success" @click="submitForm">
          <el-icon><Plus /></el-icon>
          提交
        </el-button>
      </div>
      <div class="table-inner">
        <el-table
          v-loading="loading"
          style="width: 100%"
          border
          :row-key="getRowKey"
          @row-click="clickRow"
          ref="table"
          @selection-change="handleSelectionChange"
          :data="roles.slice((pageNum - 1) * pageSize, pageNum * pageSize)"
        >
          <el-table-column type="selection" :reserve-selection="true" width="55"></el-table-column>

          <el-table-column label="序号" type="index" align="center">
            <template v-slot="scope">
              <span>{{ (pageNum - 1) * pageSize + scope.$index + 1 }}</span>
            </template>
          </el-table-column>

          <el-table-column label="角色编号" align="center" prop="roleId" />
          <el-table-column label="角色名称" align="center" prop="roleName" />
          <el-table-column label="权限字符" align="center" prop="roleKey" />

          <el-table-column
            label="创建时间"
            align="center"
            prop="createTime"
            width="180"
          ></el-table-column>
        </el-table>
      </div>

      <div class="pagination">
        <!--分页器            -->
        <el-pagination
          style="margin-top: 30px"
          v-show="total > 0"
          :total="total"
          v-model:page-size="pageSize"
          v-model:current-page="pageNum"
          layout="prev, pager, next, jumper, ->,  sizes, total"
          :page-sizes="[5, 10, 15, 20, 25, 30]"
          @current-change="handleCurrentChange"
          @size-change="handleSizeChange"
        />
      </div>
    </div>
    <RoleDrawer ref="roleDrawer" />
  </div>
</template>

<script lang="ts" setup>
  import { ElMessageBox, ElMessage, FormInstance, ElTable } from 'element-plus'
  import { getCurrentInstance, nextTick, onMounted, reactive, ref } from 'vue'
  import { Search } from '@element-plus/icons-vue'
  import RoleDrawer from './components/roleDrawer.vue'
  import { roleData } from '@/mock/system'
  import { useRoute } from 'vue-router'
  import { reqGetAuthRole, reqUpdateAuthRoleUrl } from '@/api/system/user'

  const tableData = ref()

  const roleDrawer = ref()
  const formSize = ref('default')
  const ruleFormRef = ref<FormInstance>()
  const formInline = reactive({})

  /*查询表单*/
  const form = ref({
    nickName: '',
    username: '',
    userId: 0,
  })
  const loading = ref(true) /*加载*/
  const roleIds = ref([]) // 选中角色编号
  const roles = ref([]) /*表格展示数据*/
  const pageNum = ref(1)
  const pageSize = ref(5)
  const total = ref() /*总的记录条数*/
  const table = ref<InstanceType<typeof ElTable>>()
  const $route = useRoute()
  const { proxy }: any = getCurrentInstance()

  const handleSizeChange = (val: number) => {
    console.log(`${val} items per page`)
  }
  const handleCurrentChange = (val: number) => {
    console.log(`current page: ${val}`)
  }

  const submitForm = async () => {
    console.log('submit!', formInline)
    loading.value = true

    //将信息收集起来
    const userId = form.value.userId
    const role_Ids = roleIds.value.join(',')
    await reqUpdateAuthRoleUrl({ userId: userId, roleIds: role_Ids }).then(async (req: any) => {
      if (req.code == 200) {
        proxy.$modal.msgSuccess('修改成功！')
        await init()
      } else {
        proxy.$modal.msgSuccess('修改失败！' + req.message)
      }
    })

    setTimeout(() => {
      loading.value = false
    }, 500)
  }

  /*获取行key*/
  const getRowKey = (row: any) => {
    return row.roleId
  }

  /*行点击事件*/
  const clickRow = (row: any) => {
    const findIndex = roleIds.value.indexOf(row.roleId)
    if (findIndex == -1) {
      /*userIds中没有userId*/
      table.value.toggleRowSelection(row, true)
    } else {
      /*说明已经存在了进行移除*/
      table.value.toggleRowSelection(row, false)
    }
  }

  /*全选事件*/
  const handleSelectionChange = (selection: any) => {
    roleIds.value = selection.map((item: any) => item.roleId)
  }

  /*返回按钮*/
  const close = () => {}

  /*初始化*/
  const init = async () => {
    const userId = $route.params && $route.params.userId
    if (userId) {
      loading.value = true /*遮罩层开启*/
      await reqGetAuthRole(userId).then((req: any) => {
        form.value = req.user /*对要展示的用户信息表单进行赋值*/
        roles.value = req.roles /*获取角色信息*/
        total.value = roles.value.length /*获取数据长度*/
        table.value.clearSelection() /*先清除所有*/
        nextTick(() => {
          roles.value.forEach((row: any) => {
            if (row.flag) {
              table.value.toggleRowSelection(row)
            }
          })
        })
      })
    }
  }

  onMounted(async () => {
    await init()
    setTimeout(() => {
      loading.value = false
    }, 500)
  })
</script>

<style scoped lang="scss">
  .header {
    display: flex;
    padding: 16px 16px 0px 16px;
    margin-bottom: 16px;
    border-radius: 4px;
    background: white;
    box-shadow: 0 0 12px rgb(0 0 0 / 5%);
  }
  .footer {
    flex: 1;
    display: flex;
    padding: 16px;
    flex-direction: column;
    border-radius: 4px;
    overflow: hidden;
    background: white;
    box-shadow: 0 0 12px rgb(0 0 0 / 5%);
    position: relative;
    box-sizing: border-box;
    .util {
      margin-bottom: 15px;
      display: flex;
      justify-content: flex-end;
      flex-shrink: 0;
    }
    .table-inner {
      flex: 1;
      position: relative;
    }
    .table {
      position: absolute;
      left: 0;
      top: 0;
      width: 100%;
      height: 100%;
    }
  }
</style>
